package cn.edu.anan.controller;

import cn.edu.anan.po.ThreadSafePO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 演示注入Request作为成员变量--线程不安全
 *
 * @author ThinkPad
 * @version 1.0
 * @date 2021/11/8 21:36
 */
@RestController
@RequestMapping("req")
@Slf4j
public class RequestController {

    @Autowired(required = false)
    private HttpServletRequest request;

   @Autowired
   private ThreadSafePO po;

    @RequestMapping("/test1")
    public String test1() throws  Exception{
        // 输出参数 id
        String id = request.getParameter("id");
        po.setId(Integer.parseInt(id));
        log.info("线程：{},request对象：{},请求参数Id：{}", Thread.currentThread().getName(),request.hashCode(),id);
        log.info("线程：{},request对象：{},ThreadSafePO：{}", Thread.currentThread().getName(),request.hashCode(),po.getId());

        // 休眠 10 秒
        TimeUnit.SECONDS.sleep(10);

        String id1 = request.getParameter("id");
        log.info("线程：{}休眠10s后,request对象：{},再次获取请求参数Id：{}", Thread.currentThread().getName(),request.hashCode(),id1);
        log.info("线程：{}休眠10s后,request对象：{},ThreadSafePO：{}", Thread.currentThread().getName(),request.hashCode(),po.getId());

        return "ok";
    }
}
